Skip to main content

Odd Even Linked List

LeetCode 328 | Difficulty: Medium​

Medium

Problem Description​

Given the head of a singly linked list, group all the nodes with odd indices together followed by the nodes with even indices, and return the reordered list.

The first node is considered odd, and the second node is even, and so on.

Note that the relative order inside both the even and odd groups should remain as it was in the input.

You must solve the problem in O(1) extra space complexity and O(n) time complexity.

Example 1:

Input: head = [1,2,3,4,5]
Output: [1,3,5,2,4]

Example 2:

Input: head = [2,1,3,5,6,4,7]
Output: [2,3,6,7,1,5,4]

Constraints:

- The number of nodes in the linked list is in the range `[0, 10^4]`.

- `-10^6 <= Node.val <= 10^6`

Topics: Linked List


Approach​

Linked List​

Use pointer manipulation. Common techniques: dummy head node to simplify edge cases, fast/slow pointers for cycle detection and middle finding, prev/curr/next pattern for reversal.

When to use

In-place list manipulation, cycle detection, merging lists, finding the k-th node.


Solutions​

Solution 1: C# (Best: 104 ms)​

MetricValue
Runtime104 ms
MemoryN/A
Date2018-04-17
Solution
/**
* Definition for singly-linked list.
* public class ListNode {
* public int val;
* public ListNode next;
* public ListNode(int x) { val = x; }
* }
*/
public class Solution {
public ListNode OddEvenList(ListNode head) {
if(head==null || head.next == null || head.next.next == null) return head;
ListNode odd= head, even = head.next, evenHead = even;
while(even!=null && even.next !=null)
{
odd.next = odd.next.next;
even.next = even.next.next;
odd = odd.next;
even = even.next;

}
odd.next = evenHead;
return head;
}
}

Complexity Analysis​

ApproachTimeSpace
Linked List$O(n)$$O(1)$

Interview Tips​

Key Points
  • Discuss the brute force approach first, then optimize. Explain your thought process.
  • Draw the pointer changes before coding. A dummy head node simplifies edge cases.